from datetime import datetime, timedelta

from django.db.models import Q
from django.http import JsonResponse
from django.views import View
from app.models import *
from app.url import *
from app.respositories.respositories import consumer_coins


# 获取互换记录
class IInterchangeView(View):
    def get(self, request):
        try:
            # 获取用户id
            u_id = request.GET.get('u_id', '')
            # 获取状态
            state = request.GET.get('state', '')
            # 获取所有互换记录并返回
            data = []
            # 我发起的
            if state == '0':
                idata = Interchange.objects.select_related('promoter').filter(promoter=u_id)
                for i in idata:
                    data.append({
                        'id': i.id,
                        'nickname': i.promoter.userinfo.nickname,
                        'avatar': i.promoter.userinfo.avatar,
                        'age': i.promoter.userinfo.age,
                        'height': i.promoter.userinfo.height,
                        'my_city': i.promoter.userinfo.my_city,
                        'accept': i.accept,
                        'time': i.Initiation_time
                    })
            # 被互换的
            elif state == '1':
                idata = Interchange.objects.select_related('recipient').filter(recipient=u_id)
                for i in idata:
                    data.append({
                        'id': i.id,
                        'nickname': i.recipient.userinfo.nickname,
                        'avatar': i.recipient.userinfo.avatar,
                        'age': i.recipient.userinfo.age,
                        'height': i.recipient.userinfo.height,
                        'my_city': i.recipient.userinfo.my_city,
                        'accept': i.accept,
                        'time': i.Initiation_time
                    })
            # 互换成功的
            else:
                idata = Interchange.objects.select_related('recipient').filter(
                    Q(recipient=u_id) | Q(promoter=u_id)).filter(state=1)
                for i in idata:
                    data.append({
                        'id': i.id,
                        'nickname': i.recipient.userinfo.nickname,
                        'avatar': i.recipient.userinfo.avatar,
                        'age': i.recipient.userinfo.age,
                        'height': i.recipient.userinfo.height,
                        'my_city': i.recipient.userinfo.my_city,
                        'accept': i.accept,
                        'time': i.Initiation_time
                    })
            return JsonResponse({
                'data': {
                    'result': data
                },  # 互换记录数据
                'msg': '请求成功',
                'code': 200
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'data': [],
                'msg': f'获取失败：{str(e)}'
            })

    # 添加互换记录
    def post(self, request):
        try:
            # 获取用户id
            u_id = request.POST.get('u_id', '')
            # 获取被邀请者id
            invited_id = request.POST.get('invited_id', '')
            # 消耗金币
            moneys = User.objects.select_related('gold').get(id=u_id)
            # 当前时间
            now = datetime.now()

            # 计算今天的开始和结束时间
            start_time = now.replace(hour=0, minute=0, second=0, microsecond=0)
            end_time = start_time + timedelta(days=1) - timedelta(seconds=1)

            inter = Interchange.objects.filter(promoter__id=u_id, Initiation_time__range=(start_time, end_time))
            if len(inter) >= 1:
                if moneys.gold.money >= 50:
                    # 从金币表中扣除
                    g = Gold.objects.get(id=u_id)
                    # 记录置顶前的金币
                    g.money = moneys.gold.money - 50
                    # 保存
                    g.save()
                    # 记录消费记录
                    consumer_coins({
                        'user_id': u_id,
                        'limit': 50,
                        'msg': '互换微信花费'
                    })
                    # 创建一条新的互换记录
                    Interchange.objects.create(id=uuid.uuid4(), promoter_id=u_id, recipient_id=invited_id)
                    return JsonResponse({
                        'code': 200,
                        'msg': '添加成功'
                    })
                else:
                    return JsonResponse({
                        'code': 400,
                        'msg': '金币不足'
                    })
            else:
                # 创建一条新的互换记录
                Interchange.objects.create(id=uuid.uuid4(), promoter_id=u_id, recipient_id=invited_id)
                return JsonResponse({
                    'code': 200,
                    'msg': '添加成功'
                })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'添加失败：{str(e)}'
            })


class AcceptView(View):
    # 互换微信同意或拒绝
    def post(self, request):
        try:
            print(request.POST)
            # 获取互换记录id
            i_id = request.POST.get('i_id', '')
            state = request.POST.get('state', '')
            if state == '1':
                Interchange.objects.filter(id=i_id).update(state=1)
            elif state == '2':
                Interchange.objects.filter(id=i_id).delete()
            return JsonResponse({
                'code': 200,
                'msg': '操作成功',
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'操作失败：{str(e)}'
            })
